#!/usr/bin/env python3
#coding:utf-8

__author__ = 'xmxoxo<xmxoxo@qq.com>'

'''
`mq_receive.py`

消息接收端，可设置监听指定频道，显示已收到的信息总数；
'''

from baselibs import *
from mq_lib import *

# 消息重复消费处理 2023/9/14 
obj_redis = OBJREDIS(host=redis_ip, port=redis_port, dat_table=redis_table_name)

def monitor(channel, obj_redis=None, dotask=1):
    ''' 监听消息
    '''

    print('正在连接MQ服务器: %s:%s...' % (rabbit_ip, rabbit_port) )
    # 连接MQ 
    mq = MQ(ip=rabbit_ip, port=rabbit_port)
    mq.login(rabbit_user, rabbit_pwd)

    def fun_callback(msg, dotask=dotask):
        channel = msg.get('channel', '')
        body = msg.get('body', '')
        bd_dat = json.loads(body.decode ())
        print("[%s]收到消息: %r" % (channel, bd_dat) )

        if dotask==0:
            return 1
        
        msgid = bd_dat.get('msgid', '')
        # 重复消费标志从任务中提取 【2023/10/7】
        repeat = bd_dat.get('repeat', 1)
        #print('repeat:', repeat)

        # 处理消息重复消费逻辑：repeat=0表示不允许重复
        dotask = 0
        if repeat==1:
            dotask = 1
        else:
            # print('正在判断消息是否重复消费...')
            ret = obj_redis.lock(msgid, 1)
            # print('message id:%s, ret:%s'% (msgid, ret))
            # print('ret:', type(ret), ret)
            if ret == 0:
                pass
                # print(f'{msgid}消息已经被其它服务消费!')
            elif ret == 1:
                #print('已标记消费标志，可以处理消息...')
                dotask = 1
            else:
                print('消息的消费标记尚未创建!')
        if dotask:
            print(f'任务消费处理:[{channel}]{msgid}')

        print('-'*40)

    print('正在启动消息监听，监听频道:', channel)
    mq.bind(channel, dofun=fun_callback) #, exclusive_consumption=True

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='')
    parser.add_argument('--channel', type=str, default='fj.xm.362', help='监听的频道')
    parser.add_argument('--dotask', type=int, default=1, help='是否消费消息')
    args = parser.parse_args()
    channel = args.channel
    dotask = args.dotask
    # print('channel:', channel)
    monitor(channel, obj_redis=obj_redis, dotask=dotask)

